<template>
  <div class="users-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin: 20px 0">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/home/users' }">用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 表明这个一行有分12份 -->
      <el-row :gutter="12">
        <!-- 这一块占这一行的8份 -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select" clearable>
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <!-- 这一行占这个一行的4份 -->
        <el-col :span="4">
          <!-- 点击添加用户按钮 -->
          <el-button type="primary" @click="addVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 添加用户表单信息 -->
      <el-dialog title="添加用户" :visible.sync="addVisible" class="w10" @close="closeAddDialog">
        <el-form :model="addForm" :rules="addRules" ref="addForm">
          <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" :label-width="formLabelWidth">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile" :label-width="formLabelWidth">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addVisible = false">取 消</el-button>
          <el-button type="primary" @click="define">添加</el-button>
        </div>
      </el-dialog>
      <!-- 展示分配角色 -->
      <el-dialog title="分配角色" :visible.sync="roleVisible" width="50%">
        <h4 style="margin-bottom: 10px">用 户 名: {{ role.username }}</h4>
        <h4 style="margin-bottom: 10px">当前角色: {{ role.role_name }}</h4>
        分配角色:
        <el-select v-model="selectId" filterable placeholder="请选择">
          <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="roleVisible = false">取 消</el-button>
          <el-button type="primary" @click="fenRole">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 点击编辑用户 弹窗-->
      <el-dialog title="编辑用户" :visible.sync="editVisible" class="w10" @close="closeEditDialog">
        <el-form :model="editForm" :rules="editRules" ref="editForm">
          <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile" :label-width="formLabelWidth">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser(editForm.id)">确认</el-button>
        </div>
      </el-dialog>
      <!-- 用户数据表格 -->
      <template>
        <el-table :data="newList" stripe style="width: 100%" border>
          <el-table-column type="index" label="#" width="100"> </el-table-column>
          <el-table-column prop="username" label="姓名" width="180"> </el-table-column>
          <el-table-column prop="email" label="邮箱" width="170"> </el-table-column>
          <el-table-column prop="mobile" label="电话" width="170"> </el-table-column>
          <el-table-column prop="role_name" label="角色"> </el-table-column>
          <el-table-column label="状态" width="70">
            <!-- 插槽 -->
            <!-- 可以拿到这一行的数据 -->
            <template slot-scope="scope">
              <el-switch v-model="scope.row.mg_state" @change="changeState($event, scope.row.id)"> </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <!-- 编辑用户 -->
              <el-button type="primary" icon="el-icon-edit" size="mini" @click.native="editUserById(scope.row.id)"></el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini" @click.native="remove(scope.row)"></el-button>
              <el-button type="warning" icon="el-icon-setting" size="mini" @click.native="roleShow(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>
<script>
export default {
  name: 'User',
  data() {
    // 自定义邮箱校验规则
    let checkEmail = (rules, val, cb) => {
      let EmailReg = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/
      if (!EmailReg.test(val)) {
        return cb(new Error('请输入合法的邮箱'))
      }
      // 校验成功
      return cb()
    }
    // 自定义手机号校验规则
    let checkPhone = (rules, val, cb) => {
      let phoneReg = /^(13[0-9]|[01456879]|15 [0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/

      if (!phoneReg.test(val)) {
        return cb(new Error('请输入合法的邮箱'))
      }
      // 校验成功
      return cb()
    }
    return {
      // 搜索内容
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      // 用户数据
      userList: [],
      // 总条数
      total: 0,
      // 搜索并展示的数组
      newList: [],
      addVisible: false,

      // 添加用户表单的信息
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      formLabelWidth: '70px',
      // 编辑用户信息
      // 编辑用户表单的状态
      editVisible: false,
      // 编辑用户的信息
      editForm: {},
      // 添加用户表单的验证规则
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // 使用邮箱自定义规则
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          // 使用手机号自定义规则
          { validator: checkPhone, trigger: 'blur' },
        ],
      },
      // 编辑用户表单的验证规则
      editRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // 使用邮箱自定义规则
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          // 使用手机号自定义规则
          { validator: checkPhone, trigger: 'blur' },
        ],
      },
      // 分配角色弹窗的显示或隐藏
      roleVisible: false,
      // 存放当前行角色数据
      role: {},
      // 存放角色列表
      roleList: [],
      // 选中角色的id
      selectId: '',
    }
  },
  methods: {
    // 获取用户信息
    async getUserList() {
      let { data } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      if (data.meta.status !== 200) return this.$message.err('用户数据获取失败')
      this.userList = data.data.users
      this.total = data.data.total
      // 老数组等于新数据
      this.newList = this.userList
    },
    // 改变条数
    handleSizeChange(size) {
      // 改变条数
      this.queryInfo.pagesize = size
      // 再次请求数据
      this.getUserList()
    },
    handleCurrentChange(num) {
      // 改变页数
      this.queryInfo.pagenum = num
      // 再次请求数据
      this.getUserList()
    },
    //搜索内容
    // searchCon() {
    //   this.newList = this.userList.filter((item) => {
    //     for (const key in item) {
    //       if (typeof item[key] !== 'number' && typeof item[key] !== 'boolean' && item[key] !== null) {
    //         // return
    //         if (item[key].indexOf(this.input3) > -1) {
    //           return true
    //         }
    //       }
    //     }
    //   })
    // },
    // 添加用户
    define() {
      // 校验
      this.$refs.addForm.validate(async (flag) => {
        if (!flag) return this.$message.error('请确认输入信息是否有误!')
        const { data } = await this.$http.post('users', this.addForm)
        console.log(data)
        if (data.meta.status !== 201) return this.$message.error('添加用户信息失败 请与管理员联系!')
        this.addVisible = false
        this.getUserList()
        return this.$message.success('添加成功')
      })
    },
    // 清空输入框再次发送请求
    clear() {
      this.getUserList()
    },
    // 改变状态
    async changeState(state, id) {
      let { data } = await this.$http.put(`users/${id}/state/${state}`)
      if (data.meta.status !== 200) {
        state = !state
        return this.$message.error('设置状态失败')
      }
      return this.$message.success(data.meta.msg)
    },
    // 删除用户
    remove(row) {
      this.$confirm(`是否确认删除用户${row.username}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 发起请求
          const { data } = await this.$http.delete(`users/${row.id}`)
          if (data.meta.status !== 200) return this.$message.error('删除失败 请稍后重试！')
          // 删除成功
          this.getUserList()
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
        })
        .catch((data) => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    closeAddDialog() {
      // 重置清空表单
      this.$refs.addForm.resetFields()
    },
    closeEditDialog() {
      // 重置编辑用户表单
      this.$refs.editForm.resetFields()
    },
    // 编辑用户窗口
    async editUserById(id) {
      // 展示弹窗
      this.editVisible = true
      // 发起请求
      const { data } = await this.$http.get(`users/${id}`)
      if (data.meta.status != 200) return this.$message.error('获取用户信息失败')

      // 获取用户信息成功
      this.editForm = data.data
    },
    // 点击编辑弹窗的确定按钮
    editUser(id) {
      this.$refs.editForm.validate(async (flag) => {
        if (!flag) return this.$message.error('请确认输入信息是否有误!')
        // 发请求 修改用户数据
        const { data } = await this.$http.put(`users/${id}`, this.editForm)

        if (data.meta.status != 200) return this.$message.error('更新用户信息失败 请稍后重试!')

        // 获取最新的用户数据
        this.getUserList()
        // 关闭弹窗
        this.editVisible = false
        return this.$message.success('更新成功')
      })
    },
    // 删除用户信息
    removeById(row) {
      this.$confirm(`是否确认删除用户:${row.username}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        // 发起请求
        const { data } = await this.$http.delete(`users/${row.id}`)
        if (data.meta.status !== 200) return this.$message.error('删除用户失败 请稍后重试!')
        // 删除成功 获取最新数据
        this.getUserList()
        // 提示
        this.$message({
          type: 'success',
          message: '删除成功!',
        })
      })
    },
    // 展示分配角色
    async roleShow(role) {
      // 保存当前行的用户信息 用来渲染分配角色的弹窗
      this.role = role
      // 发起请求 获取到所有的角色列表
      const { data } = await this.$http.get('roles')
      console.log(data)
      this.roleList = data.data
      this.roleVisible = true
    },
    // 点击确定按钮 分配角色
    async fenRole() {
      const { data } = await this.$http.put(`users/${this.role.id}/role`, {
        rid: this.selectId,
      })
      this.$message.success('分配权限成功')
      // 重新渲染页面
      this.getUserList()
      // 关闭弹窗
      this.roleVisible = false
    },
  },
  created() {
    this.getUserList()
  },
}
</script>
<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 20px;
}
.home-main {
  overflow: hidden;
}
.el-input {
  margin-right: 10px;
}
.el-table {
  margin-top: 20px;
  margin-bottom: 20px;
}
.el-card.is-always-shadow {
  box-shadow: 0 0 20px rgba(0, 204, 204, #000);
  height: 100%;
  .search-put {
    width: 200px;
  }
  .el-btn {
    background-color: #409eff;
  }
}
.el-dialog {
  width: 37%;
  height: 430px;
}
</style>
